import Taro, { request } from '@tarojs/taro'

import api from "./api";
import { AES } from "@util/util";


// const bseUrl = 'http://192.168.0.102:8080'
// const bseUrl = 'http://47.95.38.197:8080'
// const bseUrl = 'http://192.168.0.102:8080'
// const bseUrl = 'http://localhost:8080'
const bseUrl = 'http://dev.lightcanoe.cn:8889'

// 跳转登录页
const jump = () => {
  Taro.navigateTo({
    url: `/pages/login/index`,
  });
}

// 返回值处理
const tokenRefresh = async (code, fn) => {
  if (code == 401) {
    const refreshToken = Taro.getStorageSync("refreshToken");
    if (refreshToken) {
      const { code, data } = await api.refresh({ refreshToken: refreshToken })
      if (code == 200) {
        Taro.setStorageSync("token", AES(data.accessToken));
        Taro.setStorageSync("refreshToken", AES(data.refreshToken));
      } else {
        jump()
      }
    } else {
      jump()
    }
  } else if (code == 400) {

  } else {
    fn && fn()
  }
}

// post
const Post = (url, param = '') => {
  return new Promise((resolve, reject) => {
    request({
      url: bseUrl + url, //仅为示例，并非真实的接口地址
      data: { ...param },
      method: 'POST',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': Taro.getStorageSync('token')
      },
      success: function (res) {
        tokenRefresh(res.data.code, resolve(res.data))
      }
    })
  })
}

// postJson
const PostJson = (url, param = '') => {
  return new Promise((resolve, reject) => {
    request({
      url: bseUrl + url, //仅为示例，并非真实的接口地址
      data: { ...param },
      method: 'POST',
      dataType: 'json',
      header: {
        'content-type': 'application/json',
        'Authorization': Taro.getStorageSync('token')
      },
      success: function (res) {
        tokenRefresh(res.data.code, resolve(res.data))
      }
    })
  })
}

// get
const Get = (url, param = '') => {
  return new Promise((resolve, reject) => {
    request({
      url: bseUrl + url, //仅为示例，并非真实的接口地址
      data: { ...param },
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': Taro.getStorageSync('token')
      },
      success: function (res) {
        tokenRefresh(res.data.code, resolve(res.data))
      }
    })
  })
}

export {
  Post, Get, PostJson, bseUrl
}